<template>
  <div>
    <h1>个人中心</h1>
    <!-- 上传表单 -->
    <van-cell-group>
      <van-uploader :after-read="afterRead"> </van-uploader>
    </van-cell-group>

    <table border="1">
      <tr>
        <td>用户名</td>
        <td>{{ user_info.username }}</td>
      </tr>
      <tr>
        <td>头像</td>
        <td>
          <img
            :src="'http://127.0.0.1:8000/static/upload/' + user_info.image"
            width="100"
            height="200"
          />
        </td>
      </tr>
      <tr>
        <td>手机号</td>
        <td>{{ user_info.phone }}</td>
      </tr>
      <tr>
        <td>邮箱</td>
        <td>{{ user_info.email }}</td>
      </tr>
    </table>
    <van-field
      v-model="new_password"
      label="新密码:"
      placeholder="请输入新密码："
    ></van-field>
    <van-button type="primary" @click="changepassword">修改密码</van-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: localStorage.getItem("username"),
      jwt: localStorage.getItem("jwt"),
      user_info: {},
      new_password: "",
    };
  },
  created() {
    this.axios
      .get("http://127.0.0.1:8000/user_info?username=" + this.username)
      .then((resp) => {
        console.log(resp.data);
        this.user_info = resp.data;
      })
      .catch((error) => {
        console.log(error);
      });
  },
  methods: {
    changepassword() {
      this.axios
        .post("http://127.0.0.1:8000/comparison_token", {
          username: this.username,
          token: this.jwt,
        })
        .then((resp) => {
          console.log(resp.data);
          if (resp.data.code == 200) {
            this.axios
              .put("http://127.0.0.1:8000/change_password", {
                username: this.username,
                new_password: this.new_password,
              })
              .then((resp) => {
                console.log(resp);
              })
              .catch((error) => {
                console.log(error);
              });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 文件上传
    afterRead(file) {
      // 定义参数
      let data = new FormData();
      data.append("username", this.username);
      data.append("file", file.file);
      // 创建实例
      const axiosInstance = this.axios.create({ withCredentials: false });
      axiosInstance({
        method: "POST",
        url: "http://127.0.0.1:8000/add_image",
        data: data,
      })
        .then((resp) => {
          console.log(resp);
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style>
</style>